import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import axios from 'axios'

import { ElMessage } from 'element-plus'
import { getToken } from '@/store'
import router from '@/router'
import {LoadingService} from '@/utils'

interface axiosConfig extends AxiosRequestConfig {
  showLoading?: boolean
}

const baseURL:string = "http://10.2.220.142:5050"

export function axiosInstance(config?: axiosConfig): AxiosInstance {
  const instance = axios.create({
    baseURL:baseURL,
    timeout: 10000, // 超时配置
    withCredentials: false, // 跨域携带cookie
    ...config, // 自定义配置覆盖基本配置
  })

  const showLoading = config?.showLoading === undefined ? true : config?.showLoading

  // 添加请求拦截器
  instance.interceptors.request.use(
    (config: any) => {
      if (showLoading)
        LoadingService.open()
      if(getToken()){
        config.headers.Authorization = "Bearer "+getToken()
        config.headers.token = getToken()
      }
      return config
    },
    (error) => {
      if (showLoading)
        LoadingService.close()
      return Promise.reject(error)
    },
  )

  // 添加响应拦截器
  instance.interceptors.response.use(
    (response:any) => {
      if (showLoading)
         LoadingService.close()
      const { code,data,message} = response.data
      //後端需具體返回message，將message全部提示系統異常！
      //將data解構，不需要臃腫的response
      if (code === 200 && data.length !== 0) { return data }
      //操作類的sql返回執行成功
      else if(code === 200 && data.length === 0){
        return [ {message:'執行成功',data:[] }]
      }
      else {
        ElMessage({
          type: 'error',
          message: message,
          offset: 40,
        })
      }
    },
    (error) => {
      if (showLoading)
        LoadingService.close()
      if(error.response.status === 403){
         ElMessage({
           type:'error',
           message:'登錄失效，請重新登錄',
           offset:40
         })
         setTimeout(() => {
            router.push('/login')
         }, 1500);
      }
      else{
        ElMessage.error(error?.response?.data?.message || '服务端异常')
      }
      return Promise.reject(error)
    },
  )
  return instance
}
